package com.chaidb;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.List;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.db.DbConnection;


/**     
 *     
 * @author crystal     
 */
public class MyUploadPhoto extends HttpServlet {

	/**     
	 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.     
	 * @param request servlet request     
	 * @param response servlet response     
	 */
	// 定义文件的上传路径      
	private String uploadPath;
	private String username;
	private String markername;
	private String markerid;
	private String userid;
	private String pathsql;
	
	// 限制文件的上传大小      

	private int maxPostSize = 100 * 1024 * 1024;

	public MyUploadPhoto() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		System.out.println("Access !");
		response.setContentType("text/html;charset=UTF-8");
		String querystr = request.getQueryString();
		System.out.println(querystr);
		username = request.getParameter("username");
		markername = request.getParameter("markername");
		userid = request.getParameter("userid");
		
		uploadPath = "photos\\" + username + "\\"+ markername + "\\";
		pathsql = "\\photos\\\\" + username +
						"\\\\"+ markername + "\\\\";

		if (!new File(uploadPath).isDirectory())
			new File(uploadPath).mkdirs();
		PrintWriter out = response.getWriter();

		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(4096);
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setSizeMax(maxPostSize);
		Connection con = null;
		try {
			List fileItems = upload.parseRequest(request);
			Iterator iter = fileItems.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (!item.isFormField()) {
					String fileExt = "";
					String name = item.getName();
					int i = -1;
					if ((i = name.indexOf(".")) != -1) {
						fileExt = name.substring(i);
						name = name.substring(0, 1);
					}
					name = "" + (new Date().getTime() / 1000) + fileExt;
					System.out.println(uploadPath+name);
					try {
						item.write(new File(uploadPath + name));
						System.out.println("succeed");
						System.out.println(uploadPath + name);
						con = DbConnection.getInstance().getConnection();
						String sql2 = "select * from marker where markername='" +  markername
							+ "'&&userid='" + userid +"';";
						Statement st2 = con.createStatement();
						ResultSet query2 =st2.executeQuery(sql2);
						if(query2.next())
						{
							markerid = query2.getString("id");
							String sql = "insert into photos(markerid,photourl)values('" + markerid +"','" + pathsql + name+"');";
							System.out.println(sql);
							try {
								
								Statement st = con.createStatement();
								int rs = st.executeUpdate(sql);
								if(rs == 1)
								{
									out.println("<state>successful</state>");
								}
							}catch(SQLException e)
							{
								e.printStackTrace();
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
			System.out.println(e.getMessage() + "结束");
		}
	}

	// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">     

	/**     
	 * Handles the HTTP <code>GET</code> method.     
	 * @param request servlet request     
	 * @param response servlet response     
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**     
	 * Handles the HTTP <code>POST</code> method.     
	 * @param request servlet request     
	 * @param response servlet response     
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**     
	 * Returns a short description of the servlet.     
	 */
	public String getServletInfo() {
		return "Short description";
	}
	// </editor-fold>     

}
